package 标准接口;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;

import java.util.HashMap;
import java.util.Map;

import cn.hutool.json.JSONArray;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;




public class CreateRequestinfo20250527 {

//第一步做一次就行了  记录下来
    /**
     * 模拟缓存服务
     */
    private static final Map<String,String> SYSTEM_CACHE = new HashMap<>();

    /**
     * ecology 系统发放的授权许可证(appid)
     */
    private static final String APPID = "1e9bb811-bf63-4770-8dc1-a9f737fca11f";


    public static void main(String[] args) {

        String jsonString = HttpRequest.get("http://oa.maxwell-gp.com.cn:8090/api/fc_zh_pms/get_params?param_name=hrm_bymobile&mobile=13063863511").execute().body();

       // System.out.println(jsonString);
        String Result="";
        String Result_requestid="";

        Object succesResponse = JSON.parse(jsonString);    //先转换成Object
        Map map = (Map)succesResponse;
        String userid="";
        JSONArray jsonArray = new JSONArray(map.get("result"));
        //只取第一笔在职的
        for( int i=0;i<jsonArray.size();i++){
            JSONObject info = new JSONObject((Map<String, Object>) jsonArray.get(i));
            if("在职".equals(info.get("status"))){
            	userid=(String) info.get("id");
                break;
            }
        }
        if(!"".equals(userid)){
        	//开始调用生成接口 但是下面的那条流程我没开发起人的权限会报错  只开了你和我的
            HttpRequest.closeCookie();
            String rrr=testRestful("http://oa.maxwell-gp.com:8090","/api/workflow/paService/doCreateRequest","",userid);
            Object xxxx = JSON.parse(rrr);
            Map mapr = (Map)xxxx;

            System.out.println(rrr);
            if("SUCCESS".equals(mapr.get("code"))){
            	Map map1 = (Map)mapr.get("data"); 
             	Result="SUCCESS";
            	Result_requestid=map1.get("requestid").toString();
            }else{
            	Map map1 = (Map)mapr.get("errMsg"); 
              	Result=(String) map1.get("msg"); 
            } 
        }else{
         	Result="手机号不存在";
        }

        System.out.println("最终结果:"+Result);
        if("SUCCESS".equals(Result)){
        	//记录一下requestid
        	System.out.println(Result_requestid);
        }else{
        	//这个就是报错的原因
            System.out.println(Result);
        }
 
    }
    /**
     * 第一步：
     *
     * 调用 ecology 注册接口,根据 appid 进行注册,将返回服务端公钥和 Secret 信息
     */

    public static Map<String,Object> testGetoken(String address){
        // 从系统缓存或者数据库中获取 ECOLOGY 系统公钥和 Secret 信息

        String secret ="338f95ad-4c89-405d-9334-c1e72e2cda97";
        String spk = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCACpqY2eJhiYOIsuIgl/+Y6F5uVsAIoZRlozLXe4CvZ55Y+Exxc3Df1AY2UMorIMnGmPQ+rZkfkQQO3OJXJ1hBrhB2x2EPoOAdB8brSyQ2Z6jMhP8Fl7AYVlTm+iHS+vmXNXkgO+YD1itsnp1AYg2wIlPf+dj/tRWEgwbOqwaefQIDAQAB";

        SYSTEM_CACHE.put("SERVER_PUBLIC_KEY",spk);
        //ECOLOGY 返回的系统密钥
        SYSTEM_CACHE.put("SERVER_SECRET",secret);

        RSA rsa = new RSA(null,spk);
        //对秘钥进行加密传输，防止篡改数据
        String encryptSecret = rsa.encryptBase64(secret,CharsetUtil.CHARSET_UTF_8,KeyType.PublicKey);
        System.out.println(encryptSecret);
        //调用 ECOLOGY 系统接口进行注册
        String data = HttpRequest.post(address+ "/api/ec/dev/auth/applytoken")
                .header("appid",APPID)
                .header("secret",encryptSecret)
                .header("time","3600")
                .execute().body();
        System.out.println("testGetoken()："+data);
        Map<String,Object> datas = JSONUtil.parseObj(data);
        //ECOLOGY 返回的 token
        // TODO 为 Token 缓存设置过期时间
        SYSTEM_CACHE.put("SERVER_TOKEN", StrUtil.nullToEmpty((String)datas.get("token")));
        return datas;
    }

    public static String testRestful(String address,String api,String jsonParams,String userid){

        //ECOLOGY 返回的 token
        String token=(String) testGetoken(address).get("token");
        String spk = SYSTEM_CACHE.get("SERVER_PUBLIC_KEY");

        //封装请求头参数
        RSA rsa = new RSA(null,spk);
        //对用户信息进行加密传输,暂仅支持传输 OA 用户 ID
        String encryptUserid = rsa.encryptBase64(userid,CharsetUtil.CHARSET_UTF_8,KeyType.PublicKey);
        //调用 ECOLOGY 系统接口
        //文本里面不要放百分号进去 接口会报错 
        String body_text=
        		"workflowId=2317&requestName=CRM-报价单测试&"
                        + "mainData = ["
                        + "{'fieldName':'bjdbm','fieldValue':'报价单编码'},"//报价单编码	quote_code
                        + "{'fieldName':'bjrq','fieldValue':'2025-01-01'},"//报价日期	quote_date
                        + "{'fieldName':'sjmc','fieldValue':'商机名称'},"//商机名称	business_name
                        + "{'fieldName':'xsdb','fieldValue':'2882'},"//销售代表	company_user_id
                        + "{'fieldName':'spcjpdzd','fieldValue':'0'},"//审批层级判断字段	quote_level  [0销售代表1销售总监2部门总经理	3总裁]
                        + "{'fieldName':'khmc','fieldValue':'客'},"//客户名称	customer_name
                        + "{'fieldName':'bz','fieldValue':'0'},"//币种	field_gmsdxz [0人民币 1美元  2欧元]
                        + "{'fieldName':'lxr','fieldValue':'lxr'},"//联系人	contacts_name 
                        + "{'fieldName':'lxrdh','fieldValue':'110'},"//联系人电话	field_grngtf
                        + "{'fieldName':'lxryx','fieldValue':'110@qq.com'},"//联系人邮箱	field_vzoqyq
                        + "{'fieldName':'yxrq','fieldValue':'2025-05-01'},"//有效日期	field_kuwtso
                        
                        + "{'fieldName':'jhqx','fieldValue':'交货期限'},"//交货期限	field_jzaoea	 这个oa是文本你们再对一下吧  和那个需求文档上有点出入
                        + "{'fieldName':'jhfs','fieldValue':'0'},"//交货方式	delivery_method	  [0卖方送货至买方指定地点]
                        + "{'fieldName':'bxq','fieldValue':'1'},"//保修期	warranty_period	 [0 验收后6个月 1 验收后12个月 2 验收后24个月]
                        + "{'fieldName':'bbh','fieldValue':'版本号'},"//版本号	quote_version	文本 
                        
                        + "{'fieldName':'yxzcphjje','fieldValue':'100'},"//已选中产品，合计金额	field_rimeqt
                        + "{'fieldName':'jqtszk','fieldValue':'100'},"//减去特殊折扣	discount_price
                        + "{'fieldName':'jjzzj','fieldValue':'100'}]"//净价(最终价)	final_price


                        + "&detailData = "
                + "["

                + "{'tableDBName':'formtable_main_760_dt1','workflowRequestTableRecords':["+
                // 每一行开始
                "{'recordOrder':0,'workflowRequestTableFields':["
                + "{'fieldName':'cpmc','fieldValue':'xxx11'},"//产品名称	product_name
                + "{'fieldName':'cpxh','fieldValue':'xxx11'},"//产品型号	product_model
                + "{'fieldName':'cpggjms','fieldValue':'xxx11'},"//产品规格及描述	description
                + "{'fieldName':'pdt','fieldValue':'pdt'},"//PDT	pdt
                + "{'fieldName':'yl','fieldValue':'1'},"//用量	dosage
                + "{'fieldName':'dj','fieldValue':'1'},"//单价    文档上单位这里是单价
                + "{'fieldName':'zj','fieldValue':'1'},"//总价	subtotal
                + "]},"+
                        // 每一行结束 
                        // 每一行开始
                        "{'recordOrder':0,'workflowRequestTableFields':["
                        + "{'fieldName':'cpmc','fieldValue':'xxx22'},"//产品名称	product_name
                        + "{'fieldName':'cpxh','fieldValue':'xxx22'},"//产品型号	product_model
                        + "{'fieldName':'cpggjms','fieldValue':'xxx22'},"//产品规格及描述	description
                        + "{'fieldName':'pdt','fieldValue':'pdt'},"//PDT	pdt
                        + "{'fieldName':'yl','fieldValue':'1'},"//用量	dosage
                        + "{'fieldName':'dj','fieldValue':'1'},"//单价    文档上单位这里是单价
                        + "{'fieldName':'zj','fieldValue':'1'},"//总价	subtotal
                        + "]}"+
                        // 每一行结束 
                        "]},"
                        + "{'tableDBName':'formtable_main_760_dt4','workflowRequestTableRecords':["+
                        // 每一行开始
                        "{'recordOrder':0,'workflowRequestTableFields':["
                        + "{'fieldName':'xh','fieldValue':'1'},"//序号
                        + "{'fieldName':'lb','fieldValue':'1'},"//预付款比例（%）	advancePay 
                        + "{'fieldName':'sl','fieldValue':'2'},"//到货款比例	arrivalPay
                        + "{'fieldName':'dw','fieldValue':'3'},"//初验款比例（%）	initialPay
                        + "{'fieldName':'wsdjy','fieldValue':'4'},"//终验款比例（%）	finalPay
                        + "{'fieldName':'zbkbl','fieldValue':'5'},"//质保款比例（%）	balancePay
                        + "]},"+
                        // 每一行结束                         
                        // 每一行开始
                        "{'recordOrder':0,'workflowRequestTableFields':["
                        + "{'fieldName':'xh','fieldValue':'2'},"//序号
                        + "{'fieldName':'lb','fieldValue':'11'},"//预付款比例（%）	advancePay 
                        + "{'fieldName':'sl','fieldValue':'21'},"//到货款比例	arrivalPay
                        + "{'fieldName':'dw','fieldValue':'31'},"//初验款比例（%）	initialPay
                        + "{'fieldName':'wsdjy','fieldValue':'41'},"//终验款比例（%）	finalPay
                        + "{'fieldName':'zbkbl','fieldValue':'51'},"//质保款比例（%）	balancePay
                        + "]}"+
                        // 每一行结束 
                        "]}"
                        
                        + "]" 

                        ;
        
        
body_text="workflowId=2317&requestName=报价单申请审批"
		+ "&mainData = ["
		+ "{'fieldName':'bjdbm','fieldValue':'BJD-20250308-0129'},"
		+ "{'fieldName':'bjrq','fieldValue':'2025-03-08'},"
		+ "{'fieldName':'sjmc','fieldValue':'测试商机'},"
		+ "{'fieldName':'xsdb','fieldValue':'21574'},"
		+ "{'fieldName':'spcjpdzd','fieldValue':'1'},"
		+ "{'fieldName':'khmc','fieldValue':'CSMT'},{'fieldName':'bz','fieldValue':'人民币'},"
		+ "{'fieldName':'lxr','fieldValue':'黄丽丽'},{'fieldName':'lxrdh','fieldValue':'13500009999'},"
		+ "{'fieldName':'lxryx','fieldValue':''},{'fieldName':'yxrq','fieldValue':''},"
		+ "{'fieldName':'jhqx','fieldValue':'null'},"
		+ "{'fieldName':'jhfs','fieldValue':'0'},"
		+ "{'fieldName':'bxq','fieldValue':'1'},"
		+ "{'fieldName':'bbh','fieldValue':'null'},{'fieldName':'yxzcphjje','fieldValue':'null'},"
		+ "{'fieldName':'jqtszk','fieldValue':'20000.00'},"
		+ "{'fieldName':'jjzzj','fieldValue':'2980000.00'}]"
		+ "&detailData = [{'tableDBName':'formtable_main_760_dt1','workflowRequestTableRecords':["
		+ "{'recordOrder':0,'workflowRequestTableFields':["
		+ "{'fieldName':'cpmc','fieldValue':'测试产品2'},"
		+ "{'fieldName':'cpxh','fieldValue':'TEST-2'},"
		+ "{'fieldName':'cpggjms','fieldValue':'null'},"
		+ "{'fieldName':'pdt','fieldValue':'null'},"
		//+ "{'fieldName':'yl','fieldValue':'1'},"
		+ "{'fieldName':'dj','fieldValue':'2000000.00'},"
		+ "{'fieldName':'zj','fieldValue':'2000000.00'}]},"
		+ "{'recordOrder':0,'workflowRequestTableFields':["
		+ "{'fieldName':'cpmc','fieldValue':'测试产品1'},"
		+ "{'fieldName':'cpxh','fieldValue':'TEST-1'},"
		+ "{'fieldName':'cpggjms','fieldValue':'null'},"
		+ "{'fieldName':'pdt','fieldValue':'null'},"
		//+ "{'fieldName':'yl','fieldValue':'1'},"
		+ "{'fieldName':'dj','fieldValue':'1000000.00'},"
		+ "{'fieldName':'zj','fieldValue':'1000000.00'}]}]},"
		+ "{'tableDBName':'formtable_main_760_dt4',"
		+ "'workflowRequestTableRecords':[{'recordOrder':0,'workflowRequestTableFields':["
		+ "{'fieldName':'xh','fieldValue':'0'},"
		+ "{'fieldName':'lb','fieldValue':'40'},"
		+ "{'fieldName':'sl','fieldValue':'10'},{'fieldName':'dw','fieldValue':'10'},"
		+ "{'fieldName':'wsdjy','fieldValue':'0'},{'fieldName':'zbkbl','fieldValue':'40'}]}]}]";

        System.out.println(body_text);
        String data = HttpRequest.post(address + api)
                .header("appid", APPID)
                .header("token", token)
                .header("userid", encryptUserid)
 
                .body(body_text ).execute().body();

        System.out.println("token:" + token);
        System.out.println("userid:" + encryptUserid);
        System.out.println("testRestful" + data);
         

        return data;
    }



}
